<route lang="yaml">
meta:
enabled: false
</route>

<script setup lang="ts">
import apiAdvertisement from '@/api/modules/advertisements'
import { ElMessage, ElMessageBox } from 'element-plus'

defineOptions({
  name: 'PagesExampleMenuList',
})
const { pagination, getParams, onSizeChange, onCurrentChange } = usePagination()

const router = useRouter()

// 表格是否自适应高度
const tableAutoHeight = ref(false)

// 列表
const loading = ref(false)
const dataList = ref([])
const route = useRoute()

// 广告是否启用映射
const getstatus = (value: string) => {
  const map: Record<string, string> = {
    0: '否',
    1: '是',
  }
  return map[value] || '未知'
}

watch(
  () => route.query.timestamp,
  () => {
    if (route.name === 'PagesExampleMenuList') {
      getDataList()
    }
  },
)
onMounted(() => {
  getDataList()
})
// 搜索
const searchDefault = {
  advertisementName: '',
}
const search = ref({ ...searchDefault })
function searchReset() {
  Object.assign(search.value, searchDefault)
}

function getDataList() {
  loading.value = true
  const params = {
    advertisementName: search.value.advertisementName,
    ...(getParams()),
  }
  apiAdvertisement.list(params).then((res: any) => {
    loading.value = false
    dataList.value = res.rows
    pagination.value.total = res.total
  })
}

function onCreate(row?: any) {
  router.push({
    name: 'advertisementCreate',
    query: {
      parentId: row.id,
    },
  })
}

function onEdit(row: any) {
  router.push({
    name: 'advertisementEdit',
    params: {
      id: row.advertisementId,
    },
  })
}

function onDel(row: any) {
  ElMessageBox.confirm(`确认删除「${row.advertisementName}」吗？`, '确认信息').then(() => {
    apiAdvertisement.delete(Number(row.advertisementId)).then((res: any) => {
      if (res.code === 200) {
        getDataList()
        ElMessage.success({
          message: '删除成功',
        })
      }
    })
  }).catch(() => {})
}
// 每页数量切换
function sizeChange(size: number) {
  onSizeChange(size).then(() => getDataList())
}

// 当前页码切换（翻页）
function currentChange(page = 1) {
  onCurrentChange(page).then(() => getDataList())
}

// 照片预览
function previewImage(url: string) {
  window.open(url, '_blank')
}
</script>

<template>
  <div :class="{ 'absolute-container': tableAutoHeight }">
    <FaPageHeader title="广告管理" class="mb-0" />
    <FaPageMain :class="{ 'flex-1 overflow-auto': tableAutoHeight }" :main-class="{ 'flex-1 flex flex-col overflow-auto': tableAutoHeight }">
      <FaSearchBar :show-toggle="false">
        <template #default>
          <ElForm :model="search" size="default" label-width="100px" inline-message inline class="search-form">
            <ElFormItem label="广告名称">
              <ElInput v-model="search.advertisementName" placeholder="请输入广告名称" clearable @keydown.enter="currentChange()" @clear="currentChange()" />
            </ElFormItem>
            <ElFormItem>
              <ElButton @click="searchReset(); currentChange()">
                重置
              </ElButton>
              <ElButton v-auth="'system:user:list'" type="primary" @click="currentChange()">
                <template #icon>
                  <FaIcon name="i-ep:search" />
                </template>
                筛选
              </ElButton>
            </ElFormItem>
          </ElForm>
        </template>
      </FaSearchBar>
      <ElDivider border-style="dashed" />
      <FaPageMain :class="{ 'flex-1 overflow-auto': tableAutoHeight }" :main-class="{ 'flex-1 flex flex-col overflow-auto': tableAutoHeight }">
        <ElSpace>
          <ElButton v-auth="'system:user:add'" type="primary" size="default" @click="onCreate">
            <template #icon>
              <FaIcon name="i-ep:plus" />
            </template>
            新增广告
          </ElButton>
        </ElSpace>
        <ElTable v-loading="loading" class="mt-4" :data="dataList" row-key="id" stripe highlight-current-row default-expand-all border height="100%">
          <ElTableColumn prop="advertisementName" label="广告名称" />
          <ElTableColumn prop="advertisementTitle" label="广告主题" />
          <ElTableColumn label="广告宣传图">
            <template #default="scope">
              <div class="table-image-preview">
                <img :src="scope.row.advertisementUrl" alt="广告宣传图" @click="previewImage(scope.row.advertisementUrl)">
              </div>
            </template>
          </ElTableColumn>
          <ElTableColumn prop="status" label="作品类型">
            <template #default="scope">
              {{ getstatus(scope.row.status) }}
            </template>
          </ElTableColumn>
          <ElTableColumn label="操作" width="200" align="center" fixed="right">
            <template #default="scope">
              <ElSpace>
                <ElButton v-auth="'system:user:edit'" type="primary" size="small" plain @click="onEdit(scope.row)">
                  编辑
                </ElButton>
                <ElButton v-auth="'system:user:edit'" type="primary" size="small" plain @click="onDel(scope.row)">
                  删除
                </ElButton>
              </ElSpace>
            </template>
          </ElTableColumn>
        </ElTable>
        <ElPagination style="margin-top: 20px" :current-page="pagination.page" :total="pagination.total" :page-size="pagination.size" :page-sizes="pagination.sizes" :layout="pagination.layout" :hide-on-single-page="false" class="pagination" background @current-change="currentChange" @size-change="sizeChange" />
      </FaPageMain>
    </fapagemain>
  </div>
</template>

<style scoped>
.absolute-container {
  position: absolute;
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
}
</style>
